import pygame
from constant import *
import images
from ball import *
from result import *
from round import *

class Round :
    def __init__(self, id, max_balls) :
        self.id = id
        self.max_balls = max_balls
        self.balls = self.__createBalls__(self.max_balls)
        self.results = None
        
    def __createBalls__(self, max_balls) :
        balls = list()
        for i in xrange(max_balls) :
            balls.append(Ball(NONE, images.BALL_ROBOT, i))
        return balls
            
    def setResult(self, results) :    
        self.results = results
            
    def findBall(self, x, y) :
        if (images.BALL_ROBOT_START_X <= x <= images.BALL_ROBOT_START_X + images.SPRITE_ROBOT) :
            for i in xrange(self.max_balls) :
                if (images.BALL_ROBOT_START_Y + i * (images.SPRITE_ROBOT + images.BALL_ROBOT_DIFF) <= y <= images.BALL_ROBOT_START_Y + images.SPRITE_ROBOT + i * (images.SPRITE_ROBOT + images.BALL_ROBOT_DIFF)) :
                    y = y - images.BALL_ROBOT_START_Y
                    y = y // (images.SPRITE_ROBOT + images.BALL_ROBOT_DIFF)
                    return self.balls[y]    
        return None
            
    def previousColor(self, x, y, max_colors) :
        ball = self.findBall(x, y)
        if ball <> None:
            ball.previousColor(max_colors) 
            
    def nextColor(self, x, y, max_colors) :
        ball = self.findBall(x, y)
        if ball <> None:
            ball.nextColor(max_colors)

    def downPosition(self) :
        for ball in self.balls :
            ball.downPosition()
        for result in self.results :
            result.downPosition()
                
    def paint(self, screen) :
        for ball in self.balls :
            ball.paint(screen)
            
        if self.results <> None :
            for result in self.results :
                result.paint(screen)        
                
    def toList(self) :
        l = list()
        for ball in self.balls :
            l.append(ball.color) 
        return l
        
    def isResultCorrect(self) :
        if self.results <> None :
            for result in self.results :
                if not result.isCorrect() :
                    return False
            return True
        return False
        
    def finish(self) :
        new_balls = list()
        for ball in self.balls :
            new_ball = Ball(ball.color, images.BALL_BOARD, ball.number)
            new_balls.append(new_ball)
        self.balls = new_balls